package nerdicide.utils;

/**
 * 
 * @author Brent Kersanske
 *
 */
public class XMLModel {

	private StringBuilder model;
	private String rootName;
	private String closingElement;
	private int lastAttributeEndIndex;
	private int numChildren;

	public XMLModel(String rootName) {
		this.rootName 			   = rootName;
		this.model 				   = new StringBuilder("<"+rootName+">\n");
		this.closingElement		   = "</"+rootName+">\n";
		this.lastAttributeEndIndex = getRootNameEndIndex();
		this.numChildren		   = 0;
	}	
	
	public void addAttribute(String key, String value) {
		String newAttribute = " " + key + "=\"" + value + "\"";
		this.model.insert(this.lastAttributeEndIndex, newAttribute);
		updateLastAttributeEndIndex(newAttribute);
	}
	
	private void updateLastAttributeEndIndex(String newLastAttribute) {
		this.lastAttributeEndIndex = this.model.indexOf(newLastAttribute) + newLastAttribute.length();
	}
	
	/**
	 * 
	 * @return
	 */
	private int getRootNameEndIndex() {
		return this.model.indexOf(rootName) + rootName.length();
	}
	
	/**
	 * 
	 * @return
	 */
	private int getFirstLineEndIndex() {
		return this.model.indexOf(">\n") + 2;
	}
	
	/**
	 * 
	 * @param body
	 */
	public void insertBody(String body) {
		if(numChildren == 0) {
			this.model.insert(getFirstLineEndIndex(), body.concat(this.closingElement));
		} else {
			this.model.insert(this.model.indexOf(this.closingElement), body);
		}
	}
	
	/**
	 * 
	 * @param node
	 */
	public void addChildModel(XMLModel modelToAppend) {
		insertBody(modelToAppend.getModel());
		this.numChildren++;
	}
	
	public boolean isClosed() {
		return((this.model.indexOf("/>") != -1) && (this.model.indexOf(this.closingElement) != -1));
	}
	
	private void closeModel() {
		if(numChildren == 0) {
			this.model.insert(this.model.indexOf(">"), "/");
		} else {
			this.model.insert(this.model.length() - 2, this.closingElement);
		}
	}
	
	public String getModel() {
		if(!isClosed()) {
			closeModel();
		}
		return this.model.toString();
	}
	
	public void buildModel() {
		
	}
	
	public int getNumChildren() {
		return this.numChildren;
	}
}
